#include "data.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>

void data_clear(struct data *p)
{
    p->pnRow = 0;
    p->pnColumn = 0;
    p->i = 0;
    p->j = 0;
    p->sql = NULL;
    p->errMsg = NULL;
    p->pazResult = NULL;
}
void data_init(struct data *p,sqlite3 *ppDb)
{
    data_clear(p);
    p->ppDb = ppDb;
}

int data_query(struct data *p)
{
    if(sqlite3_get_table(p->ppDb,p->sql,&p->pazResult,&p->pnRow,&p->pnColumn,&p->errMsg) != SQLITE_OK){
        fprintf(stderr,"sqlite3_get_table:%s\n",p->errMsg);
        return -1;
    }
    //printf("%d\n",p->pnRow);
    p->i = 0;
    p->j = p->pnColumn;
    return 0;
}

int data_empty(struct data *p)
{
    //printf("%d\n%d\n",p->i,p->pnRow);
    if(p->i == p->pnRow)
        return 1;
    else 
        return 0;
}

struct value* data_get(struct data *p,struct value *v)
{
    if(data_empty(p))
        return NULL;
    
    v->data = p->pazResult + (p->j + p->i * p->j);
    v->num = p->j;
    
    p->i++;
    return v;
}